package liudan.archetype.servlet;


import liudan.archetype.bean.BeanUtils;
import liudan.archetype.xmlutil.XmlBean;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Created by liudan on 2017/2/17.
 */
public class ActionServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String path = getServletPath(request.getServletPath());
            Map<String, XmlBean> xmlBeanMap = (Map<String, XmlBean>) this.getServletContext().getAttribute("beans");
            XmlBean xmlBean = xmlBeanMap.get(path);
            Object action = BeanUtils.getBean(xmlBean.getActionType(), null);
            Method method = action.getClass().getMethod(xmlBean.getMethod(), HttpServletRequest.class);
            Object o = method.invoke(action, new Object[]{request});
            RequestDispatcher forward = request.getRequestDispatcher(o.toString());
            forward.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public String getServletPath(String servletPath) {
        return servletPath.split("\\.")[0];
    }

}
